package com.caine.algorithm.sqlTool;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @Author: CaineZhu
 * @Description:
 * @Date: Created in 16:21 2020/12/5
 * @Modified By:
 */
public class MapperTool {
    private static SqlSessionFactory sqlSessionFactory = build();

    public static SqlSessionFactory build(){
        try {
            return new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @FunctionalInterface
    public interface SessionCall<O>{
        O call(SqlSession session) throws Exception;
    }

    @FunctionalInterface
    public interface MapperCall<T, O>{
        O call(T mapper) throws Exception;
    }

   /* @FunctionalInterface
    public interface Callback<T,O>{
        O call(T mapper) throws Exception;
    }*/

    public static <T, O> O callMapper(Class<T> tClass, MapperCall<T, O> mapper) throws Exception {
        return call(session -> mapper.call(session.getMapper(tClass)));
    }

 /*   public static <T, O> O callMapper2(Class<T> tClass, Callback<T,O> callback){
        try(SqlSession sqlSession = sqlSessionFactory.openSession(true)){
            return callback.call(sqlSession.getMapper(tClass));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    public static <O> O call(SessionCall<O> sessionCall) throws Exception {
        try(SqlSession sqlSession = sqlSessionFactory.openSession(true)){
            return sessionCall.call(sqlSession);
        }


    }
}
